import { reqUserInfo } from '@/api/user'

// 子reducer
const userState = {
  token: localStorage.getItem('token') ? JSON.parse(localStorage.getItem('token')!) : '',
  userInfo: localStorage.getItem('userInfo')
    ? JSON.parse(localStorage.getItem('userInfo')!)
    : { authority: { module: '1', text: '1', choose: '1', interview: '1' } },
}

const ACTIONS = {
  Token: 'TOKEN', // 使用字符串
  UserInfo: 'USER_INFO', // 使用字符串
}

//  action creator作用是：让组件和仓库通信更优雅
export const UserActions = {
  changeToken: (token: string) => ({ type: ACTIONS.Token, payload: token }),
  changeUserInfo: (userInfo: any) => ({ type: ACTIONS.UserInfo, payload: userInfo }),
  getUserInfo: () => {
    return async (dispatch: any) => {
      const res = await reqUserInfo()
      if (res.code === 200) {
        dispatch({ type: ACTIONS.UserInfo, payload: res.data })
        localStorage.setItem('userInfo', JSON.stringify(res.data))
      }
    }
  },
}

const userReducer = function (state = userState, action: any) {
  const { type, payload } = action
  switch (type) {
    case ACTIONS.Token:
      return { ...state, token: payload }
    case ACTIONS.UserInfo:
      return { ...state, userInfo: payload }
    default:
      return state
  }
}

export default userReducer
